package org.oy.sealogger.common;

import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public final class Config {

	private static Logger log = Logger.getLogger("SeaLogger");
	private static Properties configFile = new Properties();
	
	public static final String APP_NAME = "SeaLogger";
	
	public static final String OS_LINUX	= "linux";
	public static final String OS_WIN32	= "windows";
	public static final String OS_MACOSX= "mac os x";
	
	public static final int DEVICE_DATA_WAIT_TIME = 500; //millis
	
	public static final int ARG_SIMULATE = 0;
	public static final String VAL_SIMULATE = "-s";
	
	private static String[] args;
	
	/**
	 * Initialises the Logger and Messages classes
	 */
	public static void init(String[] args) {
		Config.args = args;
		
		BasicConfigurator.configure();
		Messages.init();
		log.setLevel(Level.toLevel(Level.ALL_INT));
		
		try {
			configFile.load(Config.class.getResourceAsStream("SeaLogger.properties"));
		} catch (IOException e) {
			log.error(e);
		}
	}
	
	/**
	 * Get a logger for IO level logging
	 * @return
	 */
	public static Logger getLogger() {
		return log;
	}

	/**
	 * Get operating system name
	 * @return
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}
	
	/**
	 * Get operating system version
	 * @return
	 */
	public static String getOSVersion() {
		return System.getProperty("os.version").toLowerCase();
	}
	
	public static String getProperty(String key) {
		String arg = getByArg(key);
		
		if(arg == null)
			return configFile.getProperty(key);
		else
			return arg;
	}
	
	/**
	 * Get a property from SeaLogger.properties as an <b>unsigned</b> integer. This means
	 * any value below 0 is ignored
	 * @param key
	 * @return property indicated by the key as integer, 0 if the property is not an integer
	 * or if the property doesn't exist.
	 */
	public static int getPropertyAsInt(String key) {
		String strProperty = configFile.getProperty(key);
		int intProperty;
		
		try {
			intProperty = strProperty != null ? Integer.parseInt(strProperty) : 0;
			
			if(intProperty < 0)
				intProperty = 0;
			
		} catch(NumberFormatException e) {
			intProperty = -1;
		}
		
		return intProperty;
	}
	
	public static String getByArg(String key) {
		if(args.length >= ARG_SIMULATE + 1 && 
				key.equals("gps.device") && 
				args[ARG_SIMULATE].equals(VAL_SIMULATE))
			return "org.oy.sealogger.device.gps.GPSSimulatorDevice";
		
		return null;
	}
}
